/**
 * Created by Kpeng on 2017/7/3.
 * Depending on the jquery-1.12.4.min.js.
 * Depending on the common.js.
 * Depending on the style.min.css.
 * To cite this document, always state the source as shown above.
 * -------------------------------
 * Module:封装公共方法
 * -------------------------------
 */
if (!wzERP) {
  var wzERP = {
    //视图目录
    ViewDir: '../..',
    delayTime: 1000,
    // 公共模块
    Common: {},
    // 基础页面
    Login: {}, //登录

    //用户中心模块
    Backlog: {}, //待办事项
    Message: {}, //我的消息
    Personal: {}, //个人中心
    //订单
    Offline: {}, //线下订单
    Online: {}, //线上订单

    //基础数据模块
    ClientFiles: {},
    //基础数据模块
    Staff: {}, //员工管理
    Companies: {}, //公司管理
    Depart: {},//组织架构
    Post: {},//岗位管理
    Currency: {},//币种
    Countries: {},//国家地区
    ServiceClass: {},//服务分类
    SkuConfig: {},//SKU配置
    BusinessConfig: {},//业务配置
    //系统数据模块
    Account: {},   //账号管理
    Dict: {}, //数据词典
    Setting: {},  //系统设置
    HandleLog: {},//操作日志
    Contract: {}//操作日志
  };
}

$(function () {
  wzERP.init();
  //公共input清空
  $('.act-remove.remove').click(function () {
    $(this).siblings('input').val('')
  });

  //查询框一键清空
  $('#filter-bar').on('click', '.clear-btn', function () {
    //noraml state
    $('#filter-bar').find('input').val('');
    //citypicker
    $('#filter-bar').find('.city-picker-input').citypicker('reset');
    $('#filter-bar').find('.ui.dropdown').dropdown('clear');
    $('#filter-bar').find('select').find("option:first").attr("selected", true);
    var selects = $('#filter-bar').find('select');
    selects.change();
    selects.each(function (i, obj) {
      var text = $(obj).find("option:first").text();
      $(obj).parent().children('div .text').html(text);
      $(obj).parent().children('div .text').prop('class', 'text');
    });
  })
});

$(function () {
    wzERP.init();
    //公共input清空
    $('.act-remove.remove').click(function () {
        $(this).siblings('input').val('')
    });

    //查询框一键清空
    $('.filter-bars').on('click', '.clear-btns', function () {
        //noraml state
        $('.filter-bars').find('input').val('');
        //citypicker
        $('.filter-bars').find('.city-picker-input').citypicker('reset');
        $('.filter-bars').find('.ui.dropdown').dropdown('clear');
        $('.filter-bars').find('select').find("option:first").attr("selected", true);
        var selects = $('.filter-bars').find('select');
        selects.change();
        selects.each(function (i, obj) {
            var text = $(obj).find("option:first").text();
            $(obj).parent().children('div .text').html(text);
            $(obj).parent().children('div .text').prop('class', 'text');
        });
    })
});
wzERP.init = function () {
  wzERP.Common.autoLayout();//右边区域响应式
  wzERP.Common.accordionMenu('.org-bar-menu'); //组织架构
  wzERP.Common.dropdown('#filter-bar .ui.form');//下拉Select
  wzERP.Common.modalEdit('#main'); //判断按钮属性来显示模态框编辑形态
};

//内容高度自适
wzERP.Common.autoLayout = function () {
  var mainWrap = $('#main'),
      h1 = mainWrap.outerHeight(true) || 0,
      h2 = mainWrap.find('.filter-bar').outerHeight(true) || 0,
      h3 = mainWrap.find('.tool-bar').outerHeight(true) || 0,
      H = h1 - (h2 + h3 + 22 + 20), //margin-top:22px padding-bottom:20px
      t = null;

  mainWrap.find('.main-content').height(H);
  $(window).resize(function () {
    clearTimeout(t);

    t = setTimeout(function () {
      wzERP.Common.autoLayout();
    }, 400)
  })
};

//手风琴菜单
wzERP.Common.accordionMenu = function (_selector) {
  /*Arg Guide
   @_ele: 对象选择器
   */
  $(_selector).accordion({
    selector: {
      trigger: ".title"
    },
    duration: 200
  });
};
wzERP.Common.TimeoutLogin = function () {
  setTimeout(function () {
    if (window.parent.window != window) {
      window.top.location = "/account/login.html";
    }
    else {
      window.location.href = "/account/login.html";
    }
  }, wzERP.delayTime);
};

//表格全选和反选
wzERP.Common.checkAllTr = function (_wrap) {
  /*Arg Guide
   @_wrap: Table 对象 挂载在<table>标签
   */
  $(_wrap).each(function () {
    var master = $(this).find('th').find('.master').find('input'),  //全选外围挂.master类        sub = $(_wrap).find('tbody').find('.child').find('input');//子列表checkbox外围挂.child类
        sub = $(this).find('tbody').find('.sub').find('input'),//子列表checkbox外围挂.child类
        three = $(this).find('tbody').find('.child').find('input');//子列表checkbox外围挂.child类

    //点击一级全选框
    master.on('click', function () {
      three.prop("checked", this.checked);
    });

    //点击二级全选
    sub.on('click', function () {
      checker(this);
    });

    //点击三级子类
    if (sub.length) {  //判断是否有二级全选
      three.on('click', function () {
        checker(this);
      })
    } else {
      three.on('click', function () {
        var threeLen = three.length; //获取子three的个数
        var checkedSubLen = $(".child>input:checked").length; //获取选中的sub个数
        if (!this.checked) {
          master.prop("checked", false);
        }
        if (threeLen === checkedSubLen) {
          master.prop("checked", true);
        }
      })
    }

    function checker(ele) {
      var thisRow = $(ele).parents('tr'),  //当前行
          thisThr = thisRow.find('.child:gt(0)'), //三级
          masterCheckbox = thisRow.parents('table').find('.master').find(
              'input'),
          subCheckbox = thisRow.find('.sub').find('input'),
          thrCheckbox = thisThr.find('input'), //当前行二级
          checkedThrLen = thisThr.find('input:checked').length;  //三级选中个数

      if ($(ele).parent().hasClass('sub')) {  //操作二级
        if (ele.checked) {
          thrCheckbox.prop("checked", true);
          checkSub();
        } else {
          thrCheckbox.prop("checked", false);
          masterCheckbox.prop("checked", false);
        }
      } else { //操作三级
        if (checkedThrLen === thrCheckbox.length) {
          subCheckbox.prop("checked", true);
          checkSub();
        } else {
          subCheckbox.prop("checked", false);
          masterCheckbox.prop("checked", false);
        }
      }

      function checkSub() {  //判断二级是否选中
        var allSub = thisRow.parent('tbody').find('.sub'), //所有二级
            checkedAllSubLen = allSub.find('input:checked').length;  //更新所有选中的二级个数
        if (checkedAllSubLen === allSub.length) {
          masterCheckbox.prop("checked", true);
        } else {
          masterCheckbox.prop("checked", false);
        }
      }
    }
  })
};

//利用Modal动态装载其它页面Dom
wzERP.Common.loadHtml = function (_snippetsDir, _target, _callback) {
  /*Arg Guide
   @_snippets: 需要load进来的代码片段
   @_target: 需要load进的目标容器
   @_callback: 回调事件函数
   */
  $.ajaxSetup({
    cache: false //关闭AJAX相应的缓存
  });
  $(_target).empty().load(_snippetsDir);
  if (_callback instanceof Function) {
    setTimeout(_callback(), 300);
  }
};

//延时刷新页面
wzERP.Common.delayReload = function (_delaytime, _callback) {
  /*Arg Guide
   @_delaytime:定义多少毫秒后刷新
   @_callback:回调事件函数
   */
  setTimeout(function () {
    //修复IE是操作成功后刷新失败问题
    //  var url = $(window.parent.document).find("#inset-content-wrap").find("iframe").attr("src");
    //  location.href = url;
    if (undefined != $(".layui-laypage-btn") && $(".layui-laypage-btn").length
        != 0) {
      $(".layui-laypage-btn").click();
    }
    else {
      var url = $(window.parent.document).find("#inset-content-wrap").find(
          "iframe").attr("src"),
          forms = $(document).find("form"),
          submitForm;
      if (forms.length > 0) {
        forms.each(function (i, f) {
          var action = f.action;
          if (null != action && "" != action && (action.indexOf(url) != -1
              || url.indexOf(action) != -1)) {
            submitForm = $(f);
          }
        });
      }
      if (submitForm) {
        $(submitForm).submit();
      }
      else {
        location.href = url;
      }
    }

    // location.href = "";
    if (_callback instanceof Function) {
      _callback();
    }
  }, _delaytime);
};
wzERP.Common.isIE = function () { //ie?
  if (!!window.ActiveXObject || "ActiveXObject" in window) {
    return true;
  } else {
    return false;
  }
}
//筛选栏下拉菜单
wzERP.Common.dropdown = function () {
  var dropdown = $('.ui.dropdown');
  dropdown.dropdown({
    onChange: function (value, text, $selectedItem) {
      $(this).attr('value', value).addClass('required-hook');
      if (!!$selectedItem && $selectedItem.parents('.dropdown').length > 0) {
        $selectedItem.parents('.dropdown').removeClass('required-hook error');
      }
      //更新每页数目
      if (dropdown.hasClass('numPerPage')) {
        $('#pageSize').val(value);
      }
    }
  });
  dropdown.each(function () {
    if (this.nodeName === 'SELECT' && $(this).parent().hasClass(
            'required-hook')) {
      $(this).addClass('required-hook');
      $(this).parent().removeClass('required-hook');
    } else {
      $(this).removeClass('required-hook').find('select').addClass(
          'required-hook');
    }
  });
};

//联动起止日期
wzERP.Common.inlineDate = function (_start, _end) {
  /*Arg Guide
   @start:起始时间外围选择器
   @end:结束时间外围选择器
   */
  var startDate = $(_start),
      endDate = $(_end);
  startDate.calendar({
    type: 'date',
    today: true,
    endCalendar: endDate,
    formatter: {
      date: wzERP.Common.calendarFormatter
    }
  });
  endDate.calendar({
    type: 'date',
    startCalendar: startDate,
    formatter: {
      date: wzERP.Common.calendarFormatter
    }
  });
};

//单个日期
wzERP.Common.singleDate = function (_selector) {
  /*Arg Guide
   @_selector:触发元素对象
   */
  $(_selector).calendar({
    type: 'date',
    today: true,
    formatter: {
      date: wzERP.Common.calendarFormatter
    }
  });
};

//日期格式化：xx-yy-zz
wzERP.Common.calendarFormatter = function (date) {
  /*Arg Guide
   @date:Date()对象
   */
  if (!date) {
    return '';
  }
  var year = date.getFullYear(),
      month = date.getMonth() + 1,
      day = date.getDate();
  month = month < 10 ? '0' + month : month;
  day = day < 10 ? '0' + day : day;
  return year + '-' + month + '-' + day;
};

//内联修改表单信息
wzERP.Common.inlineEditForm = function (_option) {
  /*Arg Guide
   @ _parent:外围包裹对象选择器
   */
  var editBox = $(_option.parent).find('.edit-box');
  if (editBox) {
    $(_option.parent).on('click', '.editBtn', function () {
      var _this = $(this),//编辑按钮
          editCurBox = _this.prev('.edit-box'),//编辑框
          editText = editCurBox.prev('.val'),//当前已存值
          editInput = editCurBox.find('.edit-input');//编辑表单
      //编辑状态
      _this.hide();
      editCurBox.find('.pointing').remove().end().removeClass('error'); //清除报错状态
      editInput.val(editText.text()).attr('autofocus', true);
      editCurBox.addClass('acitve');
      //保存值
      editCurBox.on('click', '.saveBtn', function () {
        var isError = editCurBox.find('.pointing').length;  //是否有报错信息
        if (!isError) {
          editText.text(editInput.val());
          editCurBox.removeClass('acitve');
          _this.show();
          //保存回调
          if (_option.successFn instanceof Function) {
            _option.successFn();
          }
        }
      });
      //取消编辑
      editCurBox.on('click', '.cancelBtn', function () {
        editCurBox.removeClass('acitve');
        _this.show();
      })

    });
  }
};

//搜索内容
wzERP.Common.searchContent = function (_option) {
  if (Array.isArray(_option.url)) {
    $(_option.ele).search({
      source: _option.url
    });
  }
};

//判断按钮属性来显示模态框编辑形态
wzERP.Common.modalEdit = function (_parent) {
  var modalContent = $('#modalContent');
  $(_parent).on('click', '.button', function () {
    var btnType = $(this).data('type');
    (btnType === 'add' ) || (btnType === 'edit') ? modalContent.addClass(
        'editing') : modalContent.removeClass('editing');
  });
};

//提交按钮类型（参数）至后台监听按钮来源
wzERP.Common.nType = function (_option) {
  /*Arg Guide
   @ _option.parent:外围父级元素
   @ _option.url:  接口隐藏域ID
   @ _option.handle:提交操作
   */
  var modalContent = $('#modalContent'),
      url = $(_option.url).val();
  $(_option.parent).on('click', '.button', function () {
    var btnType = $(this).data('type');
    $.post(url, btnType, function () {
      if (_option.handle instanceof Function) {
        _option.handle();
      }
    }, 'json')
  });
};

//滑块开关
wzERP.Common.slideCheck = function (_option) {
  /*Arg Guide
   @ opt.ele:触发元素
   @ opt.chekcedFn: 打开时true自调
   @ opt.uncheckedFn:关闭时false自调
   */
  _option.id = $(_option.ele).parent().data('id') || "";
  _option.active = $(_option.ele).prop('checked');
  var changeAcitveUrl = $('#changeAcitveUrl').val(),
      postData = {id: _option.id, active: _option.active};

  (function () {
    $.post(changeAcitveUrl, postData, function (data) {
      switch (data.status) {
        case 0:
          layer.msg(data.msg, {icon: 2});  //成功
          break;
        case 1:
          layer.msg(data.msg, {icon: 5}); //失败
          wzERP.Common.delayReload(500);
          break;
        default:
          layer.msg(data.msg, {icon: 7});  //默认
      }
    }, 'json')
  })();
};

//Slide里的开关赋值1或0给后台
wzERP.Common.checkBoxVal = function (_selector, _errorMsg, _only) {
  /*Arg Guide
   @ _selector:触发元素
   @ _only:限制为true的个数
   */
  $(document).on('click', _selector, function () {
    if (_only) {
      var num = 0;
      $(_selector).each(function () {
        if (this.checked) {
          num += 1;
        }
      });
      if (num <= _only) {
        this.value = this.checked ? 1 : 0;
      } else {
        layer.msg(_errorMsg + _only + '个');
        return false;
      }
    } else {
      this.value = this.checked ? 1 : 0;
    }
  });
};

//标记已读
wzERP.Common.markHandle = function (_option) {
  //点击消除未读状态
  $(_option.list).on('click', '.title', function () {
    if (!$(this).hasClass('read')) {
      $(this).addClass('read')
    }
  });

  //点击标记已读
  $(_option.btn).on('click', function () {
    var checkedList = $(_option.list).find('.checkbox input:checkbox:checked'), //查找所有已经勾选的子类
        isReaded = checkedList.parents('tr').find('.title'),//信息标题
        getType = $(this).data('type');//按钮类型，多选或者全选

    if (getType === 'any') { //非全选
      if (!checkedList.length) {
        layer.msg("未勾选");  //未勾选情况
        return false;
      }
      isReaded.hasClass('read') ? layer.msg("已标记为已读") : isReaded.addClass(
          'read');
    } else if (getType === 'all') {  //全选
      var isAllChecked = $('.master').find('input:checkbox:checked').length;
      if (!isAllChecked) {  //如果没勾选
        $('.master').find('input').click();
        checkedList = $(_option.list).find('.checkbox input:checkbox:checked');
        checkedList.parents('tr').find('.title').addClass('read');
      } else {//如果已勾选
        checkedList.parents('tr').find('.title').addClass('read');
      }
    }
  });
};

//输出两个数组相同项的个数
wzERP.Common.isSame = function (_arr1, _arr2) {
  var temp = []; //临时数组1
  var temparray = [];//临时数组2
  for (var i = 0; i < _arr2.length; i++) {
    temp[_arr2[i]] = true;
  }
  for (var i = 0; i < _arr1.length; i++) {
    if (temp[_arr1[i]]) {
      temparray.push(_arr1[i]);
    }
  }
  return temparray.length;
}

/**************
 @ 数据处理
 **************/
//分页操作
wzERP.Common.pagingHandle = function (_option) {
  /*Arg Guide
   @ option.pageCurr:当前页码
   @ option.pagesTotal:总页数
   @ option.pageSize:每页条数
   @ option.pageUrl: 目标页面
   @ option.currId: 传给后台的当前页数
   */

  var pageUrl = _option.pageUrl,
      pageCurr = _option.pageCurr,
      pageSize = _option.pageSize,
      pageSearch = _option.pageSearch,
      pagesTotal = _option.pagesTotal,
      currId = _option.currId;

  $(document).on('click', '.layui-laypage a', function () {
    var getPageNum = parseInt($(this).data('page'));
    $(currId).val(getPageNum);
    $(pageSearch).action = pageUrl;
    $(pageSearch).submit();
  });

  //直接跳至指定输入的页码
  $(document).on('click', '.layui-laypage-btn', function () {
    var pageSkip = parseInt($('.layui-laypage-skip').val());
    if (pageSkip) {
      pageSkip = pageSkip > pagesTotal ? pagesTotal : pageSkip;  //超出总页数以末页输出
      $(currId).val(pageSkip);
      $(pageSearch).action = pageUrl;
      $(pageSearch).submit();
    }
  });

  //select选择每页数目
  $(document).on('click', '.page-show-select .menu .item', function () {
    var perPageNum = $(this).data('value');
    $('#pageSize').val(parseInt(perPageNum));
    $(currId).val(1);
    $(pageSearch).action = pageUrl;
    $(pageSearch).submit();
  });

  layui.use(['laypage', 'layer'], function () {
    var laypage = layui.laypage;
    laypage({
      cont: 'turn-page',
      curr: parseInt(pageCurr),
      pages: pagesTotal,
      skin: '#457fe6',
      skip: true
    });
  });
};

//模态框响应
wzERP.Common.handleData = function (_option) {
  /*Arg Guide
   @ option.ele:触发元素
   @ option.modal:模态框元素
   @ option.onApprove:“保存/确定”事件函数
   @ option.snippets:模态框内容代码片段路由
   @ option.callback:回调函数
   */
  $('#main').on('click', _option.ele, function () {
    var btnType = $(this).data('type'),  //获取挂载
        modalBox = $(_option.modalBox),
        modalHeader = modalBox.find('.header'),
        isDelete = btnType === 'delete',
        isAdd = btnType === 'add',
        getId = $(this).data('id') || ""; //获取ID ;
    //更改模态框类型
    isDelete ? modalBox.addClass('basic') : modalBox.removeClass('basic');
    _option.event = $(this);
    //将触发按钮的id绑定到模态框确定按钮上
    if (getId) {
      modalBox.find('.setId').attr('data-id', isAdd ? '' : getId);
    }
    modalBox.modal({
      closable: false,
      transition: 'fade',
      onDeny: function () {
        // 拒绝或取消
        //alert('拒绝了拒绝了拒绝了拒绝了!');
      },
      onHidden: function () {
        //关闭模态框
        $('#modal').removeAttr('style');
      },
      onApprove: function () {
        var isPass = true,
            requiredHooks = modalBox.find('.required-hook');

        //验证必填项是否符合规则
        requiredHooks.each(function () {
          var _this = $(this),
              isPrompt = _this.siblings('.prompt').length; //判断是否有未保存必填项

          console.log(this.value, this.nodeName, $(this).attr('id'));
          var id = $(this).attr('id');
          if (!this.value || isPrompt) {  //当表单为空并且有报错
            if (id == 'addCmpAddPage' || id == 'addDepartAddPage' || id
                == 'addJobAddPage') { //排除兼岗位置不通过问题
              isPass = true;
              if (this.nodeName === 'SELECT') {
                _this.parent('.dropdown').removeClass('error');
              }
              return true;
            }
            isPass = false;
            if (this.nodeName === 'SELECT') {
              _this.parent('.dropdown').addClass('error');
            } else {
              _this.parent('.required').addClass('error');
            }
            if (!this.value) {
              layer.msg('必选项不能留空白', {icon: 2});
              return false;
            }
            layer.msg('填写项不符合规则', {icon: 2});
            return false;
          } else {
            isPass = true;
            if (this.nodeName === 'SELECT') {
              _this.parent('.dropdown').removeClass('error');
            }
            return true;
          }
        });
        if (isPass && _option.onApprove instanceof Function) {
          var flag = _option.onApprove();
          if (flag === false) {
            return false;
          }
          else {
            //console.info("option.onApprove()="+flag);
          }
        } else {
          return false;
        }
      }
    }).modal('show');

    modalHeader.empty().prepend(
        '<i class="warning circle icon red"></i><span>' + _option.modalTitleStr
        + '</span>');
    isDelete ? modalHeader.addClass('del-modal-header')
        : modalHeader.removeClass('del-modal-header');
    if (_option.callback instanceof Function) {
      _option.callback();
    }
    if (_option.url) {
      _option.snippets = _option.url;
      console.log(_option.url);
    }
    wzERP.Common.loadHtml(wzERP.ViewDir + _option.snippets + "?id=" + getId,
        '#modalContent');
    console.log(wzERP.ViewDir + _option.snippets + "?id=" + getId)
  });
};

//赋值id
wzERP.Common.setIdInput = function (_option) {
  var setID = $('#modal').find('.setId').data('id');
  if (setID) {
    var getIds = setID.split(","),
        str = '';
    if (Array.isArray(_option.names)) {
      var names = _option.names;
    }
    if (getIds && names) {
      getIds.forEach(function (i, item) {
        str += '<input type="hidden" name="' + names[item] + '" value="' + i
            + '"/>';
      })
      $(_option.target).append(str);
    } else {
      $(_option.target).empty();
    }
  }
}

//提取城市三级联动数据
wzERP.Common.getCityData = function (_selector) {
  /*Arg Guide
   @ _selector:选择器对象
   */
  var selectChild = $(_selector).next('.city-picker-span').find('.title').find(
      '.select-item'),
      cityData = {};
  if (selectChild.length) {
    cityData = [
      {
        name: "id",
        value: $(_selector).data('id')
      },
      {
        name: "provinceCode",
        value: selectChild.eq(0).data('code')
      },
      {
        name: "cityCode",
        value: selectChild.eq(1).data('code')
      }, {
        name: "countyCode",
        value: selectChild.eq(2).data('code')
      }
    ];
    return cityData;
  }
};

//渲染下拉数据
wzERP.Common.renderData = function (_data, _selector) {
  /*Arg Guide
   @ _data:数据源
   @ _selector.下拉Select的ID
   */
  var temp = '';
  $.each(_data, function () {
    var name = this.name,
        val = this.value;
    temp += '<option value=' + val + '>' + name + '</option>'
  });
  $(_selector).append(temp);
};

//提交from提交操作
wzERP.Common.saveHandle = function (_formId, _url, _selector, _extendObj,
    _successFn, _errorFn) {
  console.log(111111)
  /*Arg Guide
   @ _formId:提交form的ID
   @ _url:接口地址
   @ _selector: 触发对象form
   @ _extendObj: 继承对象
   @ _errorFn: 报错的回调
   @ _successFn: 成功的回调
   */
  var formdata = $(_formId).serializeArray(), //需要提交的表单序列化
      submitUrl = $(_url).val();//获取url
  if (_selector) {
    var selectId = _selector.selector ? _selector.selector : _selector;
    var getId = $(selectId).data('id');//获取挂载ID
    if (getId) {
      formdata.unshift({name: 'id', value: getId});
    }
  }
  if (Array.isArray(_extendObj)) {
    formdata = formdata.concat(_extendObj);
  }

  console.log('员工添加', formdata);
  $.post(submitUrl, formdata, function (data) {
    switch (data.code) {
      case 0://成功
        layer.msg(data.msg, {icon: 7});
        if (_successFn instanceof Function) {
          _successFn();
        }
        break;
      case 1: //失败
        layer.msg(data.msg, {icon: 5});
        if (_errorFn instanceof Function) {
          _errorFn();
        }
        break;
      case 9999: //超时
        layer.msg(data.msg, {icon: 5});
        wzERP.Common.TimeoutLogin();
        break;
      default: //默认
        layer.msg(data.msg, {icon: 2});
        if (_errorFn instanceof Function) {
          _errorFn();
        }
    }
  }, 'json');
};

//提交ajax按需提交操作
wzERP.Common.saveAjaxHandle = function (_obj) {
  /*Arg Guide
   @ _obj.formdata:提交form的ID
   @ _obj.url:接口地址
   @ _obj.extendObj: 继承对象
   @ _obj.successFn  成功处理回调
   @ _obj.errorFn  错误处理回调
   */
  var param = _obj.param, //json数据
      submitUrl = $(_obj.url).val();//接口地址
  if (Array.isArray(_obj.extendObj)) {
    param = $.extend(param, _obj.extendObj);
  }
  console.log(JSON.stringify(param));
  $.ajax({
    type: "POST",
    url: submitUrl,
    contentType: "application/json",
    dataType: "json",
    data: JSON.stringify(param),
    success: function (data) {
      var resData = data.data;
      if (resData) {
        _obj.newId = resData.id;
      }
      switch (data.code) {
        case 0://成功
          layer.msg(data.msg, {icon: 7});
          if (_obj.successFn instanceof Function) {
            _obj.successFn();
          }
          break;
        case 1: //失败
          layer.msg(data.msg, {icon: 5});
          if (_obj.errorFn instanceof Function) {
            _obj.errorFn();
          }
          break;
        case 9999: //超时
          layer.msg(data.msg, {icon: 5});
          wzERP.Common.TimeoutLogin();
          break;
        default: //默认
          layer.msg(data.msg, {icon: 2});
          if (_obj.errorFn instanceof Function) {
            _obj.errorFn();
          }
      }
    }
  });
};

//删除操作
wzERP.Common.deleteData = function (_path, _selector) {
  /*Arg Guide
   @ _path:接口地址
   @ _ele:删除按钮
   */
  var selectId = _selector.selector ? _selector.selector : _selector;
  var delUrl = $(_path).val(),//获取删除URL
      getId = $(selectId).data('id'), //获取挂载ID
      postData = {id: getId};
  $.post(delUrl, postData, function (data) {
        switch (data.code) {
          case 0:
            layer.msg(data.msg, {icon: 7});  //成功
            wzERP.Common.delayReload(500);
            break;
          case 1:
            layer.msg(data.msg, {icon: 5}); //失败
            break;
          case 9999: //超时
            layer.msg(data.msg, {icon: 5});
            wzERP.Common.TimeoutLogin();
            break;
          default:
            layer.msg(data.msg, {icon: 2});  //默认
        }
      },
      'json');
};

////////////////////////////////////////////////////////
/**************
 @ 表格数据处理
 **************/

//@表格操作：操作单条
wzERP.Common.editTable = function (_option) {
  /*Arg Guide
   @ _option.addBtn 添加按钮
   @ _option.container tbody装载盒子
   @ _option.template 字符串模版
   @ _option.submitForm 真正提交的Form
   @ _option.saveFn  保存回调
   */

  var container = $(_option.container),  //tbody装载盒子
      rows = container.find('.row-item'), //所有行
      tempHtml = rows.eq(0).prop('outerHTML'),// 字符串模版
      curRow = null,
      editings = 0,
      isPass = false, //当前行
      wrapper = _option.wrapper ? $(_option.wrapper) : $('#modalContent');

  //条件验证，检测是否有未填或者不符合规则项
  wzERP.Common.tableVerify = function (_curRow) {
    if (_curRow) {  //点击保存时判断
      Veritify(_curRow);
    } else {  //点击新增时判断
      rows = container.find('.row-item'); //刷新行数
      if (rows.length) {
        rows.each(function () {
          Veritify($(this));
        });
      } else {
        isPass = true;
      }
    }

    //检测
    function Veritify(_obj) {
      var requireds = _obj.find('.required'),
          isPrompt = container.find('.prompt').length; //判断是否有未保存必填项
      rows = container.find('.row-item');

      if (requireds[0] && requireds[0].tagName.toLowerCase() === 'div') {
        requireds = requireds.find('select');      //解决由模版引擎自动出外盒的bug
      }
      requireds.each(function () {
        if (!this.value || isPrompt > 0) {  //当表单为空并且有报错
          isPass = false;
          layer.msg('填写项不符合规则', {icon: 2});
          return false;
        } else {
          isPass = true;
          requireds = $(this).find('.required');
          return true;
        }
      });
    }
  };

  //新增一条数据
  if (_option.addBtn) {
    wrapper.off('click').on('click', _option.addBtn, function () {
      console.log(wrapper);
      wzERP.Common.tableVerify();
      editings = container.find('.row-item.editing').length;
      if (isPass && editings === 0) {

        container.append(tempHtml);  //填充模版代码块
        if (_option.verifierFn instanceof Function) {//添加验证
          _option.verifierFn();
        }
        //处理新增加的（最后）一行
        var lastRow = container.find('.row-item').last();
        lastRow.addClass('editing new').removeAttr('data-id').find(
            _option.saveBtn).removeAttr('data-id')
        .end().find('.number').html('<i class="asterisk icon green mini"></i>');

        if (container.find('select')) {//清空下拉框
          // container.find('.selection').removeClass('required');
          container.find('.selection')
          lastRow.find('.selection').removeClass('disabled').dropdown('clear');
        }
        if (container.find('input')) {//清空输入框
          lastRow.find('input').val('')
        }
      } else {
        layer.msg('您有未保存的数据', {icon: 2});
        return false;
      }
    });
  }

  //新增子数据
  if (_option.addChildBtn) {
    container.on('click', _option.addChildBtn, function () {
      wzERP.Common.tableVerify();
      var parentId = $(this).parents('.row-item').data('id');  //父级ID
      curRow = $(this).parents('tr');
      editings = container.parents('tbody').find('.editing').length;
      if (isPass && editings === 0) {
        tempHtml = tempHtml.replace(/value=".*?"/g, 'value=""').replace(
            /data-id=".*?"/g, '');//这里tempHtml需要正则处理一下清空所有input值
        curRow.after(tempHtml);  //填充模版代码块
        curRow.next('.row-item').attr('data-pid', parentId).addClass(
            'editing new').find('.number').html(
            '<i class="asterisk icon green mini"></i>');
        if (container.find('select')) {
          wzERP.Common.dropdown();
        }
      }
    });
  }

  //保存
  if (_option.saveBtn) {
    container.on('click', _option.saveBtn, function () {
      _option.event = $(this);
      curRow = $(this).parents('tr');  //当前行
      wzERP.Common.tableVerify(curRow);
      if (isPass) {
        if (_option.submitForm) {
          $(_option.submitForm).empty().html(curRow.clone(true));
        }
        curRow.find('input').each(function () {
          var valText = $(this).siblings('.val');
          valText.text($(this).val());
        });

        curRow.find('select').parent().addClass('disabled');
        curRow.removeClass('editing new');
        if (_option.saveFn instanceof Function) {
          _option.saveFn();
        }
      }
      return false;
    });
  }

  //删除
  if (_option.delBtn) {
    container.on('click', _option.delBtn, function () {
      _option.event = $(this);
      _option.ids = $(this).parents('tr').data('id');
      console.log(_option.ids)
      layer.alert('您确定要删除该数据？', {
            title: '提示信息',
            btn: ['取消', '确认'],
            btn1: function (index) {
              layer.close(index)
            },
            btn2: function () {
              if (_option.delFn instanceof Function) {
                _option.delFn();
              }
            }
          }
      );
    });
  }

  //编辑
  if (_option.editBtn) {
    container.on('click', _option.editBtn, function () {
      curRow = $(this).parents('tr');  //当前行
      curRow.addClass('editing');
      curRow.find('select').parent().removeClass('disabled');
    });
  }

  //取消
  if (_option.cancelBtn) {
    container.on('click', _option.cancelBtn, function () {
      curRow = $(this).parents('tr');  //当前行
      if (!curRow.hasClass('new')) { //根据"new"判断是创建的还是编辑的
        // curRow.find('input').attr('disabled', true);
        curRow.find('select').parent().addClass('disabled');
        curRow.removeClass('editing');
      } else {
        curRow.remove();
      }
    });
  }
};

//表格操作：操作带复选框的单条
wzERP.Common.editCheckTable = function (_option) {
  /*Arg Guide
   @ _option.addBtn 添加按钮
   @ _option.tBody tbody装载盒子
   @ _option.template 字符串模版
   @ _option.submitForm 真正提交的Form
   @ _option.saveFn  保存回调
   */

  var submitForm = $(_option.submitForm),
      container = $(_option.container),
      tBody = container.find('tbody'),  //tbody装载盒子
      rows = tBody.find('.row-item'), //所有行
      fields = submitForm.find('.fields'), //仅表单区域
      tempHtml = rows.prop('outerHTML'),// 字符串模版
      curRow = null,
      editings = 0,
      isPass = true, //当前行
      wrapper = _option.wrapper ? $(_option.wrapper) : $('#modalContent');
  //条件验证，检测是否有未填或者不符合规则项
  wzERP.Common.tableVerify = function () {
    var isPrompt = submitForm.find('.prompt').length; //判断是否有未保存必填项
    rows = tBody.find('.row-item'); //刷新行数
    if (rows.length) {
      rows.each(function () {
        verify(this);
      });
    } else if (fields.length) {
      fields.each(function () {
        verify(this);
      })
    }

    function verify(_obj) {
      var requireds = $(_obj).find('.required');
      rows = tBody.find('.row-item'); //所有行
      requireds.each(function () {
        if (!this.value || isPrompt > 0) {  //当表单为空并且有报错
          isPass = false;
          layer.msg('请检查填写内容', {icon: 2});
          return false;
        } else {
          isPass = true;
          requireds = $(this).find('.required');
          return true;
        }
      });
    }
  };

  //是否显示删除按钮
  wzERP.Common.editTable.delIsShow = function () {
    rows = tBody.find('.row-item'); //所有行
    rows.length ? $(_option.delBtn).removeClass('disabled') : $(
        _option.delBtn).addClass('disabled');
  };
  wzERP.Common.editTable.delIsShow();

  //新增一条数据
  if (_option.addBtn) {
    wrapper.off('click').on('click', _option.addBtn, function () {
      wzERP.Common.tableVerify();
      editings = $(this).parents('tbody').find('.editing').length;
      if (isPass && editings === 0) {
        tempHtml = tempHtml.replace(/(<input.*?value=").*?(".*?\/>)/g,
            '$1$2').replace(/data-id=".*?"/g, '');//这里tempHtml需要正则处理一下清空所有input值
        tBody.append(tempHtml);
        $(_option.delBtn).show();
        //处理新增加的（最后）一行
        var lastRow = tBody.find('.row-item').last();
        lastRow.addClass('editing new').find(_option.saveBtn).removeAttr(
            'data-id');

        if (lastRow.find('select')) {
          //清空下拉框
          tBody.find('.selection').removeClass('required');
          lastRow.find('.selection').removeClass('disabled').dropdown('clear');
          wzERP.Common.dropdown();
        }
        if (lastRow.find('input')) {
          //清空输入框
          lastRow.find('input').val('')
        }
        if (lastRow.find('.custom-text')) {
          //清空输入框
          lastRow.find('.custom-text').val('')
        }
      }
    });
  }

  //保存
  if (_option.saveBtn) {
    $(document).on('click', _option.saveBtn, function () {
      wzERP.Common.tableVerify(curRow);
      var checkData = [];
      rows = tBody.find('.row-item'); //重置所有行
      curRow = $(this).parents('tr');  //当前行
      if (isPass) {
        rows.each(function () { //保存id
          checkData.push($(this).data('id'));
        });
        curRow.removeClass('editing');
        if (_option.submitForm) {
          $(_option.submitForm).find('input').each(function () {
            var valText = $(this).siblings('.val');
            valText.text($.trim($(this).val()));
          });
        }

        if (_option.saveFn instanceof Function) {
          _option.saveFn();
        }
      }
    });
  }

  //批量删除数据
  if (_option.delBtn) {
    wrapper.on('click', _option.delBtn, function () {
      var checkbox = tBody.find('.checkbox').not('.toggle'),
          checkeds = tBody.find('input[type=checkbox]:checked'),//选中的项
          noCheckeds = tBody.find('input[type=checkbox]:not(:checked)'),//未选中的项
          reserved = _option.reserved || 0,
          checkedIds = [],
          checkedData = [];
      _option.ids = '';   //初始化及清空删除ID
      if (checkeds.length) {
        if (reserved && noCheckeds.length < reserved) {
          layer.msg('请至少保留' + reserved + '条数据', {icon: 7});
          return false;
        }
        checkeds.each(function () { //保存id
          checkedIds.push($(this).parents('tr').data('id'));
        });
        checkedIds.forEach(function (i) {
          checkedData.push({'id': i})
        })

        layer.confirm('您确定要删除该数据？',
            {
              title: '提示信息',
              btn: ['取消', '确定'] //按钮
            },
            //取消事件
            function (index) {
              layer.close(index);
            },
            function () {
              _option.ids = {'ids': checkedData};//值格式
              if (_option.delFn instanceof Function) {
                _option.delFn();
              }
            });
      } else {
        layer.msg('请勾选需要删除的项', {icon: 3});
        return false;
      }
      wzERP.Common.editTable.delIsShow();
    });
  }
};

//禁用input
wzERP.Common.disabledTag = function (arr) {
  /*Arg Guide
   @ arr 需要禁止标签的name
   */
  if (Array.isArray(arr)) {
    for (var i = 0; i < arr.length; i++) {
      $('[name=' + arr[i] + ']').addClass('disabled');
    }
  }
}
/**
 * 按表名查询指定条件是否存在数据
 * @param tableName 表名
 * @param condition sql语句条件
 * @returns true 存在 ,false 不存在
 */
wzERP.Common.isExistTypeHandle = function (tableName, condition) {
  var flag = false;
  //判断类型名称是否存在
  $.ajax({
    type: "GET",
    url: '/common/uniqueQuery',
    data: 'tableName=' + tableName + '&condition=' + condition,
    async: false,
    dataType: 'json',
    success: function (data) {
      switch (data.data) {
        case 1:
          // layer.msg('类型名称已存在', {icon: 2});
          flag = true;//存在
          break;
        default:
          flag = false;//不存在
      }
    }
  });
  return flag;
}